package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.JobApplicationDTO;
import com.example.joblinker.entity.Job;
import com.example.joblinker.entity.JobApplication;
import com.example.joblinker.entity.Resume;
import com.example.joblinker.mapper.JobApplicationMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.mapper.ResumeMapper;
import com.example.joblinker.service.JobApplicationService;
import com.example.joblinker.service.UserService;
import com.example.joblinker.vo.JobApplicationVO;
import com.example.joblinker.vo.JobVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

@Service
public class JobApplicationServiceImpl implements JobApplicationService {

    @Resource
    private JobApplicationMapper jobApplicationMapper;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private ResumeMapper resumeMapper;

    @Resource
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JobApplicationVO createApplication(JobApplicationDTO jobApplicationDTO, Long userId) {
        // 检查是否已经申请过
        if (hasApplied(jobApplicationDTO.getJobId(), userId)) {
            throw new RuntimeException("您已经申请过该职位");
        }

        // 检查职位是否存在且开放
        Job job = jobMapper.selectById(jobApplicationDTO.getJobId());
        if (job == null) {
            throw new RuntimeException("职位不存在");
        }
        if (job.getStatus() != 1) {
            throw new RuntimeException("该职位已关闭");
        }

        // 创建申请
        JobApplication application = new JobApplication();
        BeanUtils.copyProperties(jobApplicationDTO, application);
        application.setUserId(userId);
        application.setStatus(0); // 待处理状态
        jobApplicationMapper.insert(application);

        // 转换为VO并返回
        return convertToVO(application);
    }

    @Override
    public JobApplicationVO getApplicationDetail(Long id) {
        JobApplication application = jobApplicationMapper.selectById(id);
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }
        return convertToVO(application);
    }

    @Override
    public Page<JobApplicationVO> getUserApplications(Long userId, Integer page, Integer size) {
        // 创建分页对象
        Page<JobApplication> applicationPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<JobApplication> queryWrapper = new LambdaQueryWrapper<JobApplication>()
                .eq(JobApplication::getUserId, userId)
                .orderByDesc(JobApplication::getCreateTime);

        // 执行查询
        jobApplicationMapper.selectPage(applicationPage, queryWrapper);

        // 转换结果
        Page<JobApplicationVO> voPage = new Page<>();
        BeanUtils.copyProperties(applicationPage, voPage, "records");
        voPage.setRecords(applicationPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    public Page<JobApplicationVO> getJobApplications(Long jobId, Integer page, Integer size) {
        // 创建分页对象
        Page<JobApplication> applicationPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<JobApplication> queryWrapper = new LambdaQueryWrapper<JobApplication>()
                .eq(JobApplication::getJobId, jobId)
                .orderByDesc(JobApplication::getCreateTime);

        // 执行查询
        jobApplicationMapper.selectPage(applicationPage, queryWrapper);

        // 转换结果
        Page<JobApplicationVO> voPage = new Page<>();
        BeanUtils.copyProperties(applicationPage, voPage, "records");
        voPage.setRecords(applicationPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateApplicationStatus(Long id, Integer status, String note) {
        // 获取申请记录
        JobApplication application = jobApplicationMapper.selectById(id);
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }

        // 更新状态
        application.setStatus(status);
        application.setProcessTime(LocalDateTime.now());
        application.setProcessNote(note);
        jobApplicationMapper.updateById(application);
    }

    @Override
    public boolean hasApplied(Long jobId, Long userId) {
        LambdaQueryWrapper<JobApplication> queryWrapper = new LambdaQueryWrapper<JobApplication>()
                .eq(JobApplication::getJobId, jobId)
                .eq(JobApplication::getUserId, userId);
        return jobApplicationMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 将实体转换为VO
     */
    private JobApplicationVO convertToVO(JobApplication application) {
        JobApplicationVO vo = new JobApplicationVO();
        BeanUtils.copyProperties(application, vo);

        // 设置职位信息
        Job job = jobMapper.selectById(application.getJobId());
        if (job != null) {
            JobVO jobVO = new JobVO();
            BeanUtils.copyProperties(job, jobVO);
            vo.setJob(jobVO);
        }

        // 设置用户名称
        vo.setUsername(userService.getUsernameById(application.getUserId()));

        // 设置简历信息
        Resume resume = resumeMapper.selectById(application.getResumeId());
        if (resume != null) {
            vo.setResume(resume);
        }

        return vo;
    }
} 